<template>
    <el-select v-model="selectedValue" filterable placeholder="请选择"  :filter-method="onFilterMethod" multiple>
        <el-checkbox v-model="checkOptions.checkAll" :style="{paddingLeft:'20px'}" :indeterminate="checkOptions.isIndeterminate" @change="onCheckAllChange">
            全选
        </el-checkbox>
        <el-option
                v-for="item in filterOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
        />
    </el-select>
</template>

<script setup lang="ts">
let props = defineProps({
    modelValue: Array
})
const checkOptions = ref({
    isIndeterminate: false,
    checkAll: false
})
const selectedValue = ref(props.modelValue)
const options = [
    {
        value: 'Option1',
        label: '小米',
    },
    {
        value: 'Option2',
        label: '大米2',
    },
    {
        value: 'Option3',
        label: '地瓜',
    },
    {
        value: 'Option4',
        label: '黄豆',
    },
    {
        value: 'Option5',
        label: '小麦',
    },
    {
        value: 'Option21',
        label: '大米1',
    }
]
const filterOptions= ref(options)
const onCheckAllChange = (e: any) => {
    selectedValue.value = e ? filterOptions.value.map(item => item.value) : []
    checkOptions.value.isIndeterminate = false
}
const onFilterMethod = (query: any) => {
    if (query !== "") {
        filterOptions.value = options.filter((item) => {
            // 这里是用的value选项筛选，默认是label
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1
        });
    } else {
        filterOptions.value = options
    }
}
const emits = defineEmits(['update:modelValue'])
watch(() => selectedValue.value, (val) => {
    const allOptions =  filterOptions.value.map(item => item.value)
    if (val!.length == 0) {
        checkOptions.value.checkAll = false
        checkOptions.value.isIndeterminate = false
    } else {
        checkOptions.value.checkAll = val!.length == allOptions.length
        checkOptions.value.isIndeterminate = val!.length != allOptions.length
    }
    emits('update:modelValue', selectedValue.value)
})
</script>

<style scoped lang="scss">

</style>
